package com.rocksea.app.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.rocksea.app.Account;
import com.rocksea.app.MyApplication;
import com.rocksea.app.PlanListActivity;
import com.rocksea.app.R;
import com.rocksea.app.UploadingListActivity;
import com.rocksea.app.UploadingTask;
import com.rocksea.app.activity.PhotoActivity;
import com.rocksea.app.activity.UploadLogsActivity;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.HighStrain.HighStrain;
import com.rocksea.app.db.PileId;
import com.rocksea.app.db.PileIdDbHelper;
import com.rocksea.app.db.SonicWave.SonicWave;
import com.rocksea.app.db.StaticLoad.StaticLoad;
import com.rocksea.app.db.UpLoadingTable;
import com.rocksea.app.db.UploadingDbHelper;
import com.rocksea.app.db.history.HistoryTable;
import com.rocksea.app.db.lowStrain.LowStrainDb;
import com.rocksea.app.entry.InspectionForm;
import com.rocksea.app.entry.Sect;
import com.rocksea.app.entry.Site;
import com.rocksea.app.http.CommHttpTask;
import com.rocksea.app.http.HttpUtil;
import com.rocksea.app.http.OnRespond;
import com.rocksea.app.http.UpLoadSonicWaveThread;
import com.rocksea.app.utils.FileHelper;
import com.rocksea.app.utils.PerUtils;
import com.rocksea.app.utils.UiUtils;
import com.rocksea.connection.OnConnectListener;
import com.rocksea.connection.RailWayOnReceiveListener;
import com.rocksea.connection.RsClient;

import com.whrsm.jar.DevMsg;
import com.whrsm.jar.RecvDevMsgListener;
import com.whrsm.jar.WhrsmJar;
import com.zbl.DZSPlatform.DownloadMessage;
import com.zbl.DZSPlatform.ReceiveMessage;
import com.zbl.server.ZBLJar;
import com.zbl.server.ZBLJarInterface;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
/**
 * @author by Mrw_v @date on 2018/9/25
 */

public class FileCenterFragment extends Fragment implements View.OnClickListener,OnConnectListener
{
    private final static String CUSTOM_NAME = "CUSTOM_NAME";
    private final static String MACHINE_NAME = "MACHINE_NAME";
    private final static String PLAN_MODE = "PLAN_MODE";
    private final static String SECT_KEY = "SECT_KEY";
    private final static String SITE_KEY = "SITE_KEY";
    public final static String PLAN_KEY = "PLAN_KEY";

    private final static String SECT_KEY_NAME_LAST = "SECT_KEY_NAME_LAST";
    private final static String SECT_KEY_ID_LAST = "SECT_KEY_ID_LAST";

    private final static String SITE_KEY_NAME_LAST = "SITE_KEY_NAME_LAST";
    private final static String SITE_KEY_ID_LAST = "SITE_KEY_ID_LAST";

    private final static String PLAN_KEY_NAME_LAST = "PLAN_KEY_NAME_LAST";
    private final static String PLAN_KEY_ID_LAST = "PLAN_KEY_ID_LAST";

    private final static String VENDOR_KEY = "TESTING_MODE_KEY";

    private final static String TESTING_KEY = "TESTING_KEY";

    private final static int RS = 0;
    private final static int ZBL = 1;
    private final static int RSM = 2;

    private final static int DC = 0;
    private final static int SC = 1;
    private final static int JY = 2;

    private final static String APP_NAME = "北京铁科院";

    @InjectView(R.id.status_bar)
    View mStatus;

    @InjectView(R.id.planType)
    View planType;

    @InjectView(R.id.bdInfo)
    View bdInfo;

    @InjectView(R.id.gdInfo)
    View gdInfo;

    @InjectView(R.id.plan)
    View plan;

    @InjectView(R.id.machine)
    View machine;

    @InjectView(R.id.state)
    View state;

    @InjectView(R.id.upLoadState)
    View uploadState;

    @InjectView(R.id.uploadLog)
    View uploadLog;

    @InjectView(R.id.machineTv)
    TextView machineTv;

    @InjectView(R.id.planTv)
    TextView planTv;

    @InjectView(R.id.planTypeTv)
    TextView planTypeTv;

    @InjectView(R.id.bdInfoTv)
    TextView bdInfoTv;

    @InjectView(R.id.gdInfoTv)
    TextView gdInfoTv;

    @InjectView(R.id.stateTv)
    TextView stateTv;

    @InjectView(R.id.upLoadStateTv)
    TextView uploadStateTv;

    @InjectView(R.id.sendPlan)
    Button sendPlan;

    @InjectView(R.id.upLoadStateInfoTv)
    TextView upLoadStateInfoTv;


    private WhrsmJar whrsmJar;
    private RsClient rsClient;

    public static FileCenterFragment newInstance()
    {
        return new FileCenterFragment();
    }

    private enum MachineType
    {
        MACHINE_RS,MACHINE_RSM,MACHINE_ZBL
    }

    private MachineType mMachineType = MachineType.MACHINE_RS;

    private enum PlanMode
    {
        bridge,road
    }

    private enum TestingMode
    {
        DC,JZ,SC
    }

    private TestingMode mTestingMode = TestingMode.DC;
    private PlanMode planMode = PlanMode.bridge;
    private ArrayList<Sect.SectBean> sectArrayList = new ArrayList<>();
    private ArrayList<Site.SiteBean> siteArrayList = new ArrayList<>();
    private ArrayList<InspectionForm.InspectionFormListBean> inspectionFormArrayList = new ArrayList<>();
    private int mSectId = 0;
    private int mSiteId = 0;
    private int mPlanId = 0;
    private String workingPlan = null;
    private TickThread mTickThread = null;
    private ArrayList<String> mUploadLogs = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState)
    {
        View mRootView = inflater.inflate(getContentViewId(),container,false);
        ButterKnife.inject(this,mRootView);
        EventBus.getDefault().register(this);

        rsClient = new RsClient(getContext(),APP_NAME,false);
        RailWayOnReceiveListener mRailWayOnReceiveListener = new RailWayOnReceiveListener();
        rsClient.setOnReceiveListener(mRailWayOnReceiveListener);

        UploadingTask.init();
        initView();
        initData();
        return mRootView;
    }

    protected void initView()
    {
        mStatus.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStateBarHeight(getActivity())));
        plan.setOnClickListener(this);
        planType.setOnClickListener(this);
        uploadState.setOnClickListener(this);
        machine.setOnClickListener(this);
        uploadLog.setOnClickListener(this);
        gdInfo.setOnClickListener(this);
        bdInfo.setOnClickListener(this);
        sendPlan.setOnClickListener(this);

        switch (PerUtils.getInt(PLAN_MODE,0))
        {
            case 0:
                planMode = PlanMode.bridge;
                planTypeTv.setText("桥梁");
                break;
            case 1:
                planTypeTv.setText("路隧");
                planMode = PlanMode.road;
                break;
        }

        // 判断用户是否是以前的
        String customName = PerUtils.getString(CUSTOM_NAME,null);
        if (customName == null || !customName.equals(Account.getAccount()))
        {
            bdInfoTv.setText("待选择标段");
            gdInfoTv.setText("待选择工点");
            planTv.setText("待选择报检单");
            planTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
            PerUtils.setString(CUSTOM_NAME,Account.getAccount());
            return;
        }

        String sectName = PerUtils.getString(SECT_KEY_NAME_LAST,null);
        int sectId = PerUtils.getInt(SECT_KEY_ID_LAST,0);
        if (sectName != null)
        {
            mSectId = sectId;
            bdInfoTv.setText(sectName);
        }

        String siteName = PerUtils.getString(SITE_KEY_NAME_LAST,null);
        int siteId = PerUtils.getInt(SITE_KEY_ID_LAST,0);
        if (siteName != null)
        {
            gdInfoTv.setText(siteName);
            mSiteId = siteId;
        }

        String planJSON = PerUtils.getString(String.format("%s$%s$%s",PLAN_KEY,sectId,siteId),null);
        String planNum = PerUtils.getString(PLAN_KEY_NAME_LAST,null);
        int planId = PerUtils.getInt(PLAN_KEY_ID_LAST,0);

        if (planJSON != null)
        {
            if (planNum != null)
            {
                planTv.setText(planNum);
                mPlanId = planId;
                workingPlan(planJSON,planNum);
            }
            handlerPlanData(planJSON,mSectId,mSiteId);
        }

        int vendor = PerUtils.getInt(VENDOR_KEY,0);
        switch (vendor)
        {
            case RS:
                mMachineType = MachineType.MACHINE_RS;
                int testingMode = PerUtils.getInt(TESTING_KEY,0);
                switch (testingMode)
                {
                    case DC:
                        mTestingMode = TestingMode.DC;
                        String machineName = PerUtils.getString(MACHINE_NAME,null);
                        if (machineName != null)
                        {
                            startRsMode(machineName);
                        }
                        break;

                    case SC:
                        mTestingMode = TestingMode.SC;
                        startRsMode("");
                        break;

                    case JY:
                        mTestingMode = TestingMode.JZ;
                        startRsMode("");
                        break;
                }
                rsClient.setPlanSheet(workingPlan);
                break;

            case ZBL:
                mMachineType = MachineType.MACHINE_ZBL;
                stateTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                stateTv.setText("已开启连接");
                machineTv.setText("智博联");
                if (rsClient != null)
                {
                    rsClient.stop();
                }
                ZBLJar.close();
                ZBLJar.setRecvDevMsgListener(zblRecvDevMsgListener,getContext());
                ZBLJar.open();
                break;

            case RSM:
                mMachineType = MachineType.MACHINE_RSM;
                stateTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                machineTv.setText("中岩");
                stateTv.setText("已开启连接");
                if (rsClient != null)
                    rsClient.stop();
                ZBLJar.close();
                whrsmJar = new WhrsmJar();
                whrsmJar.setRecvDevMsgListener(recvDevMsgListener,"",getContext());
                if (workingPlan != null)
                    whrsmJar.SetBJD(workingPlan);
                break;
        }
    }

    private void workingPlan(String planJSON, String planNum)
    {
        if (planJSON == null || planJSON.equals(""))
            return;
        try
        {
            JSONObject plan = new JSONObject(planJSON);
            JSONArray plans = plan.getJSONArray("inspectionFormList");
            for (int i = 0; i < plans.length(); i++)
            {
                if (planNum.equals(plans.getJSONObject(i).getString("number")))
                {
                    workingPlan = plans.getJSONObject(i).toString();
                }
            }
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    public int getStateBarHeight(Activity a)
    {
        int result = 0;
        int resourceId = a.getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = a.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    protected void initData()
    {
        mTickThread = new TickThread();
        mTickThread.start();
        downloadSect();
    }

    protected int getContentViewId()
    {
        return R.layout.file_center_fragment_layout;
    }

    @Override
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.planType:
                final int checkItem = PerUtils.getInt(PLAN_MODE,0);
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setSingleChoiceItems(new String[]{"桥梁", "路隧"}, checkItem, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        switch (i)
                        {
                            case 0:
                                planMode = PlanMode.bridge;
                                planTypeTv.setText("桥梁");
                                break;
                            case 1:
                                planMode = PlanMode.road;
                                planTypeTv.setText("路隧");
                                break;
                        }
                        PerUtils.setInt(PLAN_MODE,i);
                        // 与以前不同 就情空报检单列表
                        if (checkItem != i)
                        {
                            inspectionFormArrayList.clear();
                            planTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                            planTv.setText("待选择报检单");
                            UiUtils.showToast("正在更新报检单...");
                            workingPlan = null;
                            if (i == 0)
                            {
                                requestBridgeFormService(mSiteId);
                            }
                            else
                            {
                                requestRodeFormService(mSiteId);
                            }
                        }
                    }
                });
                builder.show();
                break;

            case R.id.bdInfo:
                showChooseBdInfo();
                break;

            case R.id.gdInfo:
                showChooseGdInfo();
                break;

            case R.id.plan:
                //查看和选择报检单
                if (inspectionFormArrayList.size() == 0)
                {
                    UiUtils.showToast("暂无报检单");
                    return;
                }
                Intent intent = new Intent(MyApplication.getContext(),PlanListActivity.class);
                intent.putExtra(PlanListActivity.INTENT_KEY,inspectionFormArrayList);
                intent.putExtra(PlanListActivity.CHOOSE_INDEX,mPlanId);
                int type;
                if (planMode == PlanMode.bridge)
                    type = 1;
                else
                    type = 2;
                intent.putExtra(PlanListActivity.MODE_KEY,type);
                intent.putExtra(PlanListActivity.SITE_KEY,mSiteId);
                intent.putExtra(PlanListActivity.SECT_KEY,mSectId);
                startActivity(intent);
                break;

            case R.id.machine:
                // machine name and info
                showChooseMachine();
                break;

            case R.id.upLoadState:
                // show uploading file
                Intent uploadListIntent = new Intent(getContext(), UploadingListActivity.class);
                startActivity(uploadListIntent);
                break;

            case R.id.uploadLog:
                // upload Logs activity
                if (mUploadLogs.size() == 0)
                {
                    UiUtils.showToast("暂无上传日志");
                    return;
                }
                String[] logs = new String[mUploadLogs.size()];
                for (int i = 0; i < mUploadLogs.size(); i++)
                {
                    logs[i] = mUploadLogs.get(i);
                }
                Intent uploadIntent = new Intent(getContext(), UploadLogsActivity.class);
                uploadIntent.putExtra(UploadLogsActivity.LOG_KEY,logs);
                startActivity(uploadIntent);
                break;

            case R.id.sendPlan:
                if (workingPlan == null || workingPlan.equals(""))
                {
                    showMessageDialog("请先选择一个报检单");
                    return;
                }
                switch (mMachineType)
                {
                    case MACHINE_RS:
                        if (rsClient == null)
                        {
                            showMessageDialog("请先开启连接");
                            return;
                        }
                        rsClient.setPlanSheet(workingPlan);
                        UiUtils.showToast("报检单下发成功");
                        break;

                    case MACHINE_RSM:
                        if (whrsmJar == null)
                        {
                            showMessageDialog("请先开启连接");
                            return;
                        }
                        whrsmJar.SetBJD(workingPlan);
                        UiUtils.showToast("报检单下发成功");
                        break;

                    case MACHINE_ZBL:
                        String[] loginDev = ZBLJar.getLoginDevs();
                        showMachineListDialog(loginDev,workingPlan);
                        break;

                    default:
                        break;
                }
        }
    }

    private void showMessageDialog(String message)
    {
        AlertDialog.Builder errorDialog = new AlertDialog.Builder(getActivity());
        errorDialog.setTitle("提示");
        errorDialog.setIcon(android.R.drawable.ic_dialog_alert);
        errorDialog.setMessage(message);
        errorDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        errorDialog.show();
    }
    private void showMachineListDialog(final String[] machineNames, final String planStr)
    {
        if (machineNames == null || machineNames.length == 0)
        {
            UiUtils.showToast("暂无在线设备");
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("选择下发的设备");
        builder.setSingleChoiceItems(machineNames, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                DownloadMessage downloadMessage =  new DownloadMessage();
                downloadMessage.devNo = machineNames[which];
                downloadMessage.inspectionFormStr = planStr;
                int returnCode = new ZBLJarInterface().download(downloadMessage);
                if(returnCode == 0)
                {
                    UiUtils.showToast("发送报检单成功");
                }
                else
                {
                    UiUtils.showToast("发送报检单失败");
                }
            }
        });
        builder.show();
    }

    private class ChooseMachineDialog extends android.support.v7.app.AlertDialog
    {

        public ChooseMachineDialog(@NonNull Context context)
        {
            super(context);
        }

        public ChooseMachineDialog(@NonNull Context context, int themeResId)
        {
            super(context, themeResId);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            Window window = getWindow();
            if (window!=null)
            {
                WindowManager m = getWindow().getWindowManager();
                Display d = m.getDefaultDisplay();
                WindowManager.LayoutParams p = getWindow().getAttributes();
                p.width = d.getWidth()-60;
                getWindow().setAttributes(p);
            }
        }

    }

    private void showChooseMachine()
    {
        ChooseMachineDialog.Builder chooseMachineDialog = new ChooseMachineDialog.Builder(getContext());
        chooseMachineDialog.setTitle("设置采集设备");

        chooseMachineDialog.setView(R.layout.choose_machine_dialog_layout);
        View chooseMachineView = View.inflate(getContext(),R.layout.choose_machine_dialog_layout,null);
        chooseMachineDialog.setView(chooseMachineView);

        final RadioGroup vendorRadioGroup = (RadioGroup) chooseMachineView.findViewById(R.id.vendorRadioGroup);
        RadioButton rsRadioButton = (RadioButton) chooseMachineView.findViewById(R.id.RS);
        RadioButton rsmRadioButton = (RadioButton) chooseMachineView.findViewById(R.id.RSM);
        RadioButton zblRadioButton = (RadioButton) chooseMachineView.findViewById(R.id.ZBL);

        final RadioGroup machineRadioGroup = (RadioGroup) chooseMachineView.findViewById(R.id.machineRadioGroup);
        RadioButton jyRadioButton = (RadioButton) chooseMachineView.findViewById(R.id.JZ);
        RadioButton scmRadioButton = (RadioButton) chooseMachineView.findViewById(R.id.SC);
        RadioButton dclRadioButton = (RadioButton) chooseMachineView.findViewById(R.id.DC);

        final View rsMachine = chooseMachineView.findViewById(R.id.rsMachine);
        final AutoCompleteTextView inputMachineCode = (AutoCompleteTextView) chooseMachineView.findViewById(R.id.MachineId);

        switch (mMachineType)
        {
            case MACHINE_RS:
                rsRadioButton.setChecked(true);
                break;

            case MACHINE_RSM:
                rsmRadioButton.setChecked(true);
                rsMachine.setVisibility(View.GONE);
                break;

            case MACHINE_ZBL:
                zblRadioButton.setChecked(true);
                rsMachine.setVisibility(View.GONE);
                break;
        }

        switch (mTestingMode)
        {
            case SC:
                scmRadioButton.setChecked(true);
                inputMachineCode.setVisibility(View.GONE);
                break;

            case JZ:
                jyRadioButton.setChecked(true);
                inputMachineCode.setVisibility(View.GONE);
                break;

            case DC:
                dclRadioButton.setChecked(true);
                inputMachineCode.setVisibility(View.VISIBLE);
                inputMachineCode.setText(PerUtils.getString(MACHINE_NAME,""));
                break;
        }

        vendorRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                switch (checkedId)
                {
                    case R.id.RS:
                        rsMachine.setVisibility(View.VISIBLE);
                        break;

                    case R.id.RSM:
                        rsMachine.setVisibility(View.GONE);
                        break;

                    case R.id.ZBL:
                        rsMachine.setVisibility(View.GONE);
                        break;
                }
            }
        });

        machineRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                switch (checkedId)
                {
                    case R.id.JZ:
                        inputMachineCode.setVisibility(View.GONE);
                        break;

                    case R.id.DC:
                        inputMachineCode.setVisibility(View.VISIBLE);
                        inputMachineCode.setText(PerUtils.getString(MACHINE_NAME,""));
                        break;

                    case R.id.SC:
                        inputMachineCode.setVisibility(View.GONE);
                        break;
                }
            }
        });

        chooseMachineDialog.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                switch (vendorRadioGroup.getCheckedRadioButtonId())
                {
                    case R.id.RS:
                        ZBLJar.close();
                        mMachineType = MachineType.MACHINE_RS;
                        PerUtils.setInt(VENDOR_KEY,RS);
                        switch (machineRadioGroup.getCheckedRadioButtonId())
                        {
                            case R.id.JZ:
                                mTestingMode = TestingMode.JZ;
                                startRsMode("");
                                break;

                            case R.id.SC:
                                mTestingMode = TestingMode.SC;
                                startRsMode("");
                                break;

                            case R.id.DC:
                                mTestingMode = TestingMode.DC;
                                String machineName = inputMachineCode.getText().toString().trim();
                                startRsMode(machineName);
                                break;
                        }
                        break;

                    case R.id.ZBL:
                        mMachineType = MachineType.MACHINE_ZBL;
                        machineTv.setText("智博联");
                        stateTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                        stateTv.setText("已开启连接");
                        if (rsClient != null)
                        {
                            rsClient.stop();
                        }
                        ZBLJar.close();
                        ZBLJar.setRecvDevMsgListener(zblRecvDevMsgListener,getContext());
                        ZBLJar.open();
                        PerUtils.setInt(VENDOR_KEY,ZBL);
                        break;

                    case R.id.RSM:
                        mMachineType = MachineType.MACHINE_RSM;
                        if (rsClient != null)
                        {
                            rsClient.stop();
                        }
                        ZBLJar.close();
                        machineTv.setText("中岩");
                        stateTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                        stateTv.setText("已开启连接");
                        whrsmJar = new WhrsmJar();
                        whrsmJar.setRecvDevMsgListener(recvDevMsgListener,"",getContext());
                        PerUtils.setInt(VENDOR_KEY,RSM);
                        break;
                }

            }
        });
        chooseMachineDialog.show();
    }


    @Override
    public void onDestroy()
    {
        if (rsClient != null)
            rsClient.stop();
        ZBLJar.close();
        if (mTickThread != null)
        {
            mTickThread.quit();
            mTickThread = null;
        }
        UpLoadSonicWaveThread.exitUploadThread();
        UploadingTask.cancel();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void showChooseGdInfo()
    {
        if (siteArrayList.size() == 0)
        {
            UiUtils.showToast("暂无工点信息");
            return;
        }
        final String[] item = new String[siteArrayList.size()];
        int checkedIndex = 0;
        for (int i = 0; i < siteArrayList.size(); i++)
        {
            item[i] = siteArrayList.get(i).name;
            if (mSiteId == siteArrayList.get(i).id)
                checkedIndex = i;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setSingleChoiceItems(item, checkedIndex, new CustomDialogSingleChoiceItemListener(checkedIndex,item));
        builder.show();
    }
    private void showChooseBdInfo()
    {
        if (sectArrayList.size() == 0)
        {
            UiUtils.showToast("暂无标段");
            return;
        }
        int checkIndex = 0;
        final String[] item = new String[sectArrayList.size()];
        for (int i = 0; i < sectArrayList.size(); i++)
        {
            item[i] = sectArrayList.get(i).name;
            if (mSectId == sectArrayList.get(i).id)
            {
                checkIndex = i;
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setSingleChoiceItems(item, checkIndex, new CustomDialogInterfaceOnClickListener(checkIndex,item));
        builder.show();
    }

    private class CustomDialogSingleChoiceItemListener implements DialogInterface.OnClickListener
    {
        private int checkedIndex;
        private String[] item;

        private CustomDialogSingleChoiceItemListener(int checkedIndex, String[] item)
        {
            this.checkedIndex = checkedIndex;
            this.item = item;
        }

        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            if (which != checkedIndex)
            {
                dialog.dismiss();
                gdInfoTv.setText(item[which]);
                UiUtils.showToast("正在更新报检单信息...");
                mSiteId = siteArrayList.get(which).id;

                inspectionFormArrayList.clear();
                workingPlan = null;
                mPlanId = 0;

                PerUtils.setString(SITE_KEY_NAME_LAST,item[which]);
                PerUtils.setInt(SITE_KEY_ID_LAST,mSiteId);
                switch (planMode)
                {
                    case road:
                        requestRodeFormService(siteArrayList.get(which).id);
                        break;
                    case bridge:
                        requestBridgeFormService(siteArrayList.get(which).id);
                        break;
                }

            }

        }
    }

    private class CustomDialogInterfaceOnClickListener implements DialogInterface.OnClickListener
    {
        private int checkedIndex;
        private String[] item;

        CustomDialogInterfaceOnClickListener(int checkedIndex,String[] item)
        {
            this.checkedIndex = checkedIndex;
            this.item = item;
        }

        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            dialog.dismiss();
            if (checkedIndex != which)
            {
                bdInfoTv.setText(item[which]);
                gdInfoTv.setText("待选择工点");
                siteArrayList.clear();
                planTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                planTv.setText("待选择报检单");
                inspectionFormArrayList.clear();

                mPlanId = 0;
                workingPlan = null;

                mSectId = sectArrayList.get(which).id;
                PerUtils.setString(SECT_KEY_NAME_LAST,item[which]);
                PerUtils.setInt(SECT_KEY_ID_LAST,mSectId);
                downSiteBySectId(mSectId);
                UiUtils.showToast("正在更新工点信息...");
            }
        }
    }


    private void downloadSect()
    {
        LinkedHashMap<String,Object> mRequest = new LinkedHashMap<>();
        mRequest.put("in0",Account.getRandomCode());
        HttpUtil.http(CommHttpTask.DOWN_SECT,mRequest,mDownSectRespond);
    }

    private void downSiteBySectId(long sectId)
    {
        LinkedHashMap<String,Object> mRequest = new LinkedHashMap<>();
        mRequest.put("in0",Account.getRandomCode());
        mRequest.put("in1",String.valueOf(sectId));
        HttpUtil.http(CommHttpTask.DOWN_SITE,mRequest,new DownSiteRespond(sectId));
    }

    private OnRespond mDownSectRespond = new OnRespond()
    {
        @Override
        public void onSucceed(String json)
        {
            Log.d("sect = ",json);
            try
            {
                Sect sect = JSON.parseObject(json, Sect.class);
                if (!sect.flag.equals("0"))
                {
                    json = PerUtils.getString(SECT_KEY,null);
                    if (json == null)
                    {
                        UiUtils.showToast("更新标段失败");
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                json = PerUtils.getString(SECT_KEY,null);
                if (json == null)
                {
                    UiUtils.showToast("更新标段失败");
                    return;
                }
            }
            handlerSectData(json);
        }

        private void handlerSectData(String json)
        {
            Sect sect = JSON.parseObject(json, Sect.class);
            if (sect.flag.equals("0"))
            {
                UiUtils.showToast("更新标段成功");
                PerUtils.setString(SECT_KEY,json);
                sectArrayList.clear();
                sectArrayList.addAll(sect.sectList);
                if (sectArrayList.size() > 0)
                {
                    if (mSectId == 0)
                    {
                        bdInfoTv.setText(sectArrayList.get(0).name);
                        downSiteBySectId(sectArrayList.get(0).id);
                        //保存 最新的id&name
                        PerUtils.setString(SECT_KEY_NAME_LAST,sectArrayList.get(0).name);
                        PerUtils.setInt(SECT_KEY_ID_LAST,sectArrayList.get(0).id);
                        mSectId = sectArrayList.get(0).id;
                    }
                    else
                    {
                        downSiteBySectId(mSectId);
                    }
                }
            }
        }

        @Override
        public void onError(int code, String error)
        {
            String json = PerUtils.getString(SECT_KEY,"");
            if (json.equals(""))
            {
                UiUtils.showToast(String.format("(%s)%s",error,code));
                return;
            }
            handlerSectData(json);
        }
    };


    private class DownSiteRespond implements OnRespond
    {
        private long sectId;

        DownSiteRespond(long sectId)
        {
            this.sectId = sectId;
        }

        @Override
        public void onSucceed(String json)
        {
            Log.d("sect = ",json);
            try
            {
                Site site = JSON.parseObject(json,Site.class);
                if (!site.flag.equals("0"))
                {
                    json = PerUtils.getString(String.format("%s$%s",SITE_KEY,sectId),"");
                    if (json.equals(""))
                    {
                        UiUtils.showToast(String.format("获取工点失败(%s)",json));
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                json = PerUtils.getString(String.format("%s$%s",SITE_KEY,sectId),"");
                if (json.equals(""))
                {
                    UiUtils.showToast(String.format("获取工点失败(%s)",json));
                    return;
                }
            }
            handlerSiteData(json);
        }

        private void handlerSiteData(String json)
        {
            Site site = JSON.parseObject(json,Site.class);
            UiUtils.showToast("更新工点成功");
            PerUtils.setString(String.format("%s$%s",SITE_KEY,sectId),json);
            siteArrayList.clear();
            siteArrayList.addAll(site.siteList);
            if (siteArrayList.size() > 0) // 不主动选择工点
            {
                if (mSiteId == 0)
                {
                    mSiteId = siteArrayList.get(0).id;
                    gdInfoTv.setText(siteArrayList.get(0).name);
                    PerUtils.setString(SITE_KEY_NAME_LAST,siteArrayList.get(0).name);
                    PerUtils.setInt(SITE_KEY_ID_LAST,siteArrayList.get(0).id);
                    switch (planMode)
                    {
                        case bridge:
                            requestBridgeFormService(siteArrayList.get(0).id);
                            break;

                        case road:
                            requestRodeFormService(siteArrayList.get(0).id);
                            break;
                    }
                }
            }
        }

        @Override
        public void onError(int code, String error)
        {
            String json = PerUtils.getString(String.format("%s$%s",SITE_KEY,sectId),"");
            if (json.equals(""))
            {
                UiUtils.showToast(String.format("(%s)%s",error,code));
                return;
            }
            handlerSiteData(json);
        }
    }


    private void requestRodeFormService(int siteId)
    {
        LinkedHashMap<String,Object> mRequest = new LinkedHashMap<>();
        mRequest.put("in0", Account.getRandomCode());
        mRequest.put("in1",String.valueOf(mSectId));
        mRequest.put("in2",String.valueOf(siteId));
        mRequest.put("in3",PerUtils.dateToStr(new Date(new Date().getTime()-DbCenter.DAY_OF_TIME*30*12)));
        mRequest.put("in4",PerUtils.dateToStr(new Date()));
        HttpUtil.http(CommHttpTask.DOWN_INSPECTION_FROM_1,mRequest,new DownLoadPlanRespond(mSectId,siteId));
    }


    private void requestBridgeFormService(int siteId)
    {
        LinkedHashMap<String,Object> mRequest = new LinkedHashMap<>();
        mRequest.put("in0", Account.getRandomCode());
        mRequest.put("in1",String.valueOf(mSectId));
        mRequest.put("in2",String.valueOf(siteId));
        mRequest.put("in3",PerUtils.dateToStr(new Date(new Date().getTime()-DbCenter.DAY_OF_TIME*30*12)));
        mRequest.put("in4",PerUtils.dateToStr(new Date()));
        HttpUtil.http(CommHttpTask.DOWN_INSPECTION_FROM,mRequest,new DownLoadPlanRespond(mSectId,siteId));
    }


    private class DownLoadPlanRespond implements OnRespond
    {
        private long sectId;
        private long siteId;

        DownLoadPlanRespond(long sectId,long siteId)
        {
            this.sectId = sectId;
            this.siteId = siteId;
        }

        @Override
        public void onSucceed(String json)
        {
            Log.e("plan ",json);
            try
            {
                InspectionForm mInspectionForm = JSON.parseObject(json, InspectionForm.class);
                if (!mInspectionForm.flag.equals("0"))
                {
                    json = PerUtils.getString(String.format("%s$%s$%s",PLAN_KEY,sectId,siteId),null);
                    if (json == null)
                    {
                        UiUtils.showToast("更新报检单失败");
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                json = PerUtils.getString(String.format("%s$%s$%s",PLAN_KEY,sectId,siteId),null);
                if (json == null)
                {
                    UiUtils.showToast("更新报检单失败");
                    return;
                }
            }
            handlerPlanData(json,sectId,siteId);
        }
        @Override
        public void onError(int code, String error)
        {
            String json = PerUtils.getString(String.format("%s$%s$%s",PLAN_KEY,sectId,siteId),null);
            if (json == null)
            {
                UiUtils.showToast("当前工点暂无报检单");
                return;
            }
            handlerPlanData(json,sectId,siteId);
        }
    }

    private void handlerPlanData(String json,long sectId,long siteId)
    {
        InspectionForm mInspectionForm = JSON.parseObject(json, InspectionForm.class);
        if (mInspectionForm.flag.equals("0"))
        {
            PerUtils.setString(String.format("%s$%s$%s",PLAN_KEY,sectId,siteId),json);
            if (mInspectionForm.inspectionFormList == null || mInspectionForm.inspectionFormList.size() == 0)
            {
                UiUtils.showToast("暂无报检单");
                inspectionFormArrayList.clear();
                planTv.setTextColor(ContextCompat.getColor(getContext(),R.color.gark_40));
                planTv.setText("暂无报检单");
                return;
            }
            // 保存至本地 数据库
            DbCenter.savePileId(mInspectionForm.inspectionFormList);
            inspectionFormArrayList.clear();
            inspectionFormArrayList.addAll(mInspectionForm.inspectionFormList);
            if (inspectionFormArrayList.size() > 0)
            {
                if (mPlanId == 0)
                {
                    planTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                    planTv.setText("待选择报检单");
                }
            }
            UiUtils.showToast("更新报检单完成");
        }
    }

    @Override
    public void onStatusChanged(int i, String s)
    {
        switch (i)
        {
            case STATUS_BT_OFF:
            case STATUS_BT_DISCONNECTED:
            case STATUS_STOP:
                stateTv.setTextColor(ContextCompat.getColor(getContext(),R.color.gark_40));
                break;

            case STATUS_BT_SCANNING:
            case STATUS_BT_CONNECTED:
            case STATUS_BT_CONNECTING:
            case STATUS_START:
            case STATUS_WAIT_FOR_CONNECT:
                stateTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                break;
        }
        stateTv.setText(s);
    }

    @Override
    public void onMachineConnected(int i, String s)
    {
        switch (mTestingMode)
        {
            case JZ:
                machineTv.setText(String.format("武汉岩海静载(%s)",s));
                break;

            case SC:
                machineTv.setText(String.format("武汉岩海声测(%s)",s));
                break;

            case DC:
                machineTv.setText(String.format("武汉岩海动测(%s)",s));
                break;
        }
        stateTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
        stateTv.setText("连接成功");
    }

    @Override
    public void onMachineDisconnected(int i, String s)
    {
        stateTv.setText("连接断开,正在重试连接...");
        stateTv.setTextColor(ContextCompat.getColor(getContext(),android.R.color.holo_red_dark));
    }

    @Override
    public boolean onException(int i, String s)
    {
        return false;
    }

    @Override
    public void onReceive(int i, String s, int i1, Object o)
    {
        if ((o == null) || !(o instanceof String))
            return;
        String data = o.toString();
        switch (i1)
        {
            case OnConnectListener.DATA_DYB_TASK_INFO:
                DbCenter.save(addId(data),DbCenter.LOWSTARIN);
                break;

            case OnConnectListener.DATA_DYB_DATA:
                DbCenter.save(data,DbCenter.LOWSTARIN_DATA);
                break;

            case OnConnectListener.DATA_DYB_FINISHED:
                DbCenter.save(data,DbCenter.LOWSTARIN_END);
                break;

            case OnConnectListener.DATA_SC_TASK_INFO:
                DbCenter.save(addId(data),DbCenter.SONICWAVE);
                break;

            case OnConnectListener.DATA_SC_SECTION_INFO:
                DbCenter.save(data,DbCenter.SONICWAVE_FACE);
                break;

            case OnConnectListener.DATA_SC_WAVE_DATA:
                DbCenter.save(data,DbCenter.SONICWAVE_DATA);
                break;

            case OnConnectListener.DATA_SC_FINISHED:
                DbCenter.save(data,DbCenter.SNOICWAVE_END);
                break;

            case OnConnectListener.DATA_JZ_TASK_INFO:
                DbCenter.save(addId(data),DbCenter.STATICLOAD);
                break;

            case OnConnectListener.DATA_JZ_RECORD:
                DbCenter.save(data,DbCenter.STATICLOAD_DATA);
                break;

            case OnConnectListener.DATA_JZ_LOG:
                DbCenter.save(data,DbCenter.STATICLOAD_LOG);
                break;

            case OnConnectListener.DATA_JZ_FINISHED:
                DbCenter.save(data,DbCenter.STATICLOAD_END);

                break;
            case OnConnectListener.DATA_GYB_DATA:
                DbCenter.save(addId(data),DbCenter.HIGHSTRAIN);
                break;

            default:
                break;
        }
    }

    // add pileId & planId
    private String addId(String data)
    {
        try
        {
            JSONObject info = new JSONObject(data);
            String pileNo = info.getString("PileNo");
            String planNum = info.getString("SerialNo");
            PileId pileId = PileIdDbHelper.queryPlanIdAndPileId(planNum,pileNo);
            info.put("pileId",pileId.pileId);
            info.put("inspectionFormId",(int)pileId.planId);
            info.put("inspectionFormNum",pileId.planNum);
            return info.toString();
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        return data;
    }

    //中研数据回调
    private RecvDevMsgListener recvDevMsgListener = new RecvDevMsgListener()
    {
        @Override
        public void onRecvDevMsg(DevMsg devMsg)
        {
            try
            {
                switch (devMsg.ContentType)
                {
                    case DevMsg.CONTENT_LOWSTRAIN:
                        DbCenter.save(addId(devMsg.msg),DbCenter.LOWSTARIN);
                        break;

                    case DevMsg.CONTENT_LOWSTRAIN_DATA:
                        DbCenter.save(devMsg.msg,DbCenter.LOWSTARIN_DATA);
                        break;

                    case DevMsg.CONTENT_LOWSTRAIN_END:
                        DbCenter.save(devMsg.msg,DbCenter.LOWSTARIN_END);
                        break;

                    case DevMsg.CONTENT_SONICWAVE:
                        DbCenter.save(addId(devMsg.msg),DbCenter.SONICWAVE);
                        break;

                    case DevMsg.CONTENT_SONICWAVE_FACE:
                        DbCenter.save(devMsg.msg,DbCenter.SONICWAVE_FACE);
                        break;

                    case DevMsg.CONTENT_SONICWAVE_DATA:
                        DbCenter.save(devMsg.msg,DbCenter.SONICWAVE_DATA);
                        break;

                    case DevMsg.CONTENT_SONICWAVE_END:
                        DbCenter.save(devMsg.msg,DbCenter.SNOICWAVE_END);
                        break;

                    case DevMsg.CONTENT_STATICLOAD:
                        DbCenter.save(addId(devMsg.msg),DbCenter.STATICLOAD);
                        break;

                    case DevMsg.CONTENT_STATICLOAD_DATA:
                        DbCenter.save(devMsg.msg,DbCenter.STATICLOAD_DATA);
                        break;

                    case DevMsg.CONTENT_STATICLOAD_LOG:
                        DbCenter.save(devMsg.msg,DbCenter.STATICLOAD_LOG);
                        break;

                    case DevMsg.CONTENT_STATICLOAD_END:
                        DbCenter.save(devMsg.msg,DbCenter.STATICLOAD_END);
                        break;

                    case DevMsg.CONTENT_HIGHSTRAIN:
                        DbCenter.save(devMsg.msg,DbCenter.HIGHSTRAIN);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                UiUtils.showToast(String.format("解析中岩数据异常(%s)",devMsg.ContentType));
                new FileHelper().wirteCrash("RSM_Crash",e.toString());
            }
        }
    };

    // 智博联 数据回调
    private com.zbl.server.RecvDevMsgListener zblRecvDevMsgListener = new com.zbl.server.RecvDevMsgListener()
    {
        @Override
        public void onRecvDevMsg(ReceiveMessage msg)
        {
            try
            {
                Gson gson = new Gson();
                ReceiveMessage receiveMessage = gson.fromJson(msg.toJson(), ReceiveMessage.class);
                String action = receiveMessage.action;
                if (action.equalsIgnoreCase("LOGIN"))
                {
                    String[] machineNames = ZBLJar.getLoginDevs();
                    final StringBuilder builder = new StringBuilder();
                    for (String machineName : machineNames)
                    {
                        builder.append(machineName);
                        builder.append(",");
                    }
                    builder.deleteCharAt(builder.length()-1);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() { machineTv.setText(String.format("智博联(%s)",builder.toString())); }
                    });
                }
                else if (action.equalsIgnoreCase("LowStrainFinish"))
                {
                    DbCenter.save(null,DbCenter.LOWSTARIN_END);
                }
                else if (action.equalsIgnoreCase("SonicWaveFinish"))
                {
                    DbCenter.save(null,DbCenter.SNOICWAVE_END);
                }
                else if (receiveMessage.action.equalsIgnoreCase("LowStrainParam"))
                {
                    DbCenter.save(addId(receiveMessage.data),DbCenter.LOWSTARIN);
                }
                else if (receiveMessage.action.equalsIgnoreCase("LowStrainData"))
                {
                    DbCenter.save(receiveMessage.data,DbCenter.LOWSTARIN_DATA);
                }
                else if (receiveMessage.action.equalsIgnoreCase("SonicWaveParam"))
                {
                    DbCenter.save(addId(receiveMessage.data),DbCenter.SONICWAVE);
                }
                else if (receiveMessage.action.equalsIgnoreCase("SonicWaveSection"))
                {
                    DbCenter.save(receiveMessage.data,DbCenter.SONICWAVE_FACE);
                }
                else if (receiveMessage.action.equalsIgnoreCase("SonicWaveData"))
                {
                    DbCenter.save(receiveMessage.data,DbCenter.SONICWAVE_DATA);
                }
            }
            catch (final Exception e)
            {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UiUtils.showToast("解析智博联数据异常");
                        new FileHelper().wirteCrash("ZBL",e.toString());
                    }
                });
            }
        }
    };

    private void startRsMode(String machineName)
    {
        if (rsClient != null)
        {
            rsClient.stop();
            switch (mTestingMode)
            {
                case DC:
                    rsClient.start(OnConnectListener.DEVICE_DC_BLUETOOTH,machineName,this);
                    PerUtils.setInt(TESTING_KEY,DC);
                    machineTv.setText(String.format("武汉岩海动测(%s)",machineName));
                    PerUtils.setString(MACHINE_NAME,machineName);
                    break;

                case SC:
                    rsClient.start(OnConnectListener.DEVICE_SC_WIFI,"",this);
                    PerUtils.setInt(TESTING_KEY,SC);
                    machineTv.setText("武汉岩海声测");
                    break;

                case JZ:
                    rsClient.start(OnConnectListener.DEVICE_JZ_WIFI,"",this);
                    PerUtils.setInt(TESTING_KEY,JY);
                    machineTv.setText("武汉岩海静载");
                    PerUtils.setInt(TESTING_KEY,JY);
                    break;
            }
        }
        else
        {
            UiUtils.showToast("请先启动岩海模式");
        }
    }

    public static class StateEvent
    {
        public String message;

        public StateEvent() {}
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStateEvent(StateEvent stateEvent)
    {
        stateTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
        stateTv.setText(stateEvent.message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChoosePlanEvent(PlanListActivity.ChoosePlanEvent choosePlanEvent)
    {
        if (choosePlanEvent.mInspectionFormListBeans != null)
        {
            inspectionFormArrayList.clear();
            inspectionFormArrayList.addAll(choosePlanEvent.mInspectionFormListBeans);
            return;
        }
        planTv.setText(choosePlanEvent.formListBean.number);
        PerUtils.setString(PLAN_KEY_NAME_LAST,choosePlanEvent.formListBean.number);
        PerUtils.setInt(PLAN_KEY_ID_LAST,choosePlanEvent.formListBean.id);
        String planJSON = PerUtils.getString(String.format("%s$%s$%s",PLAN_KEY,mSectId,mSiteId),null);
        if (planJSON != null)
        {
            if (choosePlanEvent.formListBean.number != null)
            {
                mPlanId = choosePlanEvent.formListBean.id;
                workingPlan(planJSON,choosePlanEvent.formListBean.number);
            }
        }
        if (rsClient != null)
            rsClient.setPlanSheet(workingPlan);
        if (whrsmJar != null)
            whrsmJar.SetBJD(workingPlan);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTick(TickThread.Tick tick)
    {
        uploadStateTv.setText(String.format("待上传数据 %s 条",tick.count));
    }

    // uploading data task thread
    private class TickThread extends Thread
    {
        private boolean isPostEvent = true;

        private void quit()
        {
            if (isAlive())
            {
                interrupt();
                try {
                    join(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run()
        {
            while (!isInterrupted())
            {
                long count = UploadingDbHelper.queryCount();
                EventBus.getDefault().post(new Tick(count));
                UpLoadingTable mUpLoadingTable = UploadingDbHelper.queryFirstTable();
                if (mUpLoadingTable != null)
                {
                    if (mUpLoadingTable.isUploading == 0)
                    {
                        // 采样数据和日志数据以及完成实验指令
                        if (mUpLoadingTable.mode == HistoryTable.JY_SAMPLE_DATA || mUpLoadingTable.mode == HistoryTable.JY_LOG_DATA)
                        {
                            mUpLoadingTable.mode = HistoryTable.TEST_JZ;
                        }
                        // 发送上传事件
                        if (isPostEvent)
                        {
                            EventBus.getDefault().post(new QueryTask(mUpLoadingTable.baseInfoId,mUpLoadingTable.mode));
                            isPostEvent = false;
                        }
                    }
                    else
                    {
                        UploadingDbHelper.delete(mUpLoadingTable.baseInfoId,mUpLoadingTable.mode,mUpLoadingTable.uuid);
                        isPostEvent = true;
                    }
                }
                try
                {
                    sleep(1000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                    break;
                }
            }
        }
        public class Tick
        {
            private long count;
            public Tick() {}
            private Tick(long count)
            {
                this.count = count;
            }
        }

        public class QueryTask
        {
            public String baseInfoId;
            public int mode;

            public QueryTask(String baseInfoId, int mode) {
                this.baseInfoId = baseInfoId;
                this.mode = mode;
            }
            public QueryTask(){}
        }
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onQueryTask(TickThread.QueryTask queryTask)
    {
        switch (queryTask.mode)
        {
            case HistoryTable.TEST_DY:
                HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"正在加载数据...");
                LowStrainDb lowStrainDb = DbCenter.mDyDbHelper.queryAllLowStarinData(queryTask.baseInfoId);
                if (lowStrainDb == null)
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,"未能查询到数据");
                    UploadingDbHelper.makeUnloading(queryTask.baseInfoId,HistoryTable.TEST_DY,UpLoadingTable.DEFAULT_UUID);
                    return;
                }
                EventBus.getDefault().post(lowStrainDb);
                break;

            case HistoryTable.TEST_GY:
                HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"正在加载数据...");
                String data =  DbCenter.mGyDbHelper.queryJSON(queryTask.baseInfoId);
                if (data == null)
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,"未能查询到数据");
                    UploadingDbHelper.makeUnloading(queryTask.baseInfoId,HistoryTable.TEST_GY,UpLoadingTable.DEFAULT_UUID);
                    return;
                }
                HighStrain highStrain = new HighStrain(data);
                PileId pileId = DbCenter.mGyDbHelper.queryPileId(queryTask.baseInfoId);
                highStrain.inspectionFormId = pileId.planId;
                highStrain.inspectionFormNum = pileId.planNum;
                highStrain.pileId = pileId.pileId;
                EventBus.getDefault().post(highStrain);
                break;

            case HistoryTable.TEST_JZ:
                HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"正在加载数据...");
                StaticLoad staticLoad = DbCenter.mStaticLoadDbHelper.queryById(queryTask.baseInfoId);
                if (staticLoad == null)
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,"未能查询到数据");
                    UploadingDbHelper.makeUnloading(queryTask.baseInfoId,HistoryTable.TEST_JZ,UpLoadingTable.DEFAULT_UUID);
                    return;
                }
                EventBus.getDefault().post(staticLoad);
                break;

            case HistoryTable.TEST_SC:
                HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"正在加载数据...");
                // 上传声测数据
                SonicWave sonicWaves = DbCenter.mScDbHelper.querySonicWave(queryTask.baseInfoId);
                if (sonicWaves == null)
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,"未能查询到数据");
                    UploadingDbHelper.makeUnloading(queryTask.baseInfoId,HistoryTable.TEST_SC,UpLoadingTable.DEFAULT_UUID);
                    return;
                }
                if (sonicWaves.SonicWaveFaces == null || sonicWaves.SonicWaveFaces.size() == 0)
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,"数据不完整无法上传");
                    UploadingDbHelper.makeUnloading(queryTask.baseInfoId,HistoryTable.TEST_SC,UpLoadingTable.DEFAULT_UUID);
                    return;
                }

                UpLoadSonicWaveThread upLoadSonicWaveThread = new UpLoadSonicWaveThread(sonicWaves,getContext());
                upLoadSonicWaveThread.start();
                break;
        }
    }

    @SuppressLint("ResourceAsColor")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadEvent(HttpUtil.UploadEvent uploadEvent)
    {
        switch (uploadEvent.level)
        {
            case HttpUtil.UploadEvent.ERROR:
                upLoadStateInfoTv.setTextColor(ContextCompat.getColor(getContext(),android.R.color.holo_red_dark));
                break;
            case HttpUtil.UploadEvent.NORMAL:
                upLoadStateInfoTv.setTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
                break;
            case HttpUtil.UploadEvent.WARM:
                upLoadStateInfoTv.setTextColor(ContextCompat.getColor(getContext(),android.R.color.holo_orange_light));
                break;
        }
        upLoadStateInfoTv.setText(uploadEvent.message);
        if (mUploadLogs.size() > 1000)
            mUploadLogs.clear();
        mUploadLogs.add(String.format("%s %s",uploadEvent.time,uploadEvent.message));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadLowStrainDb(LowStrainDb lowStrainDb)
    {
        UploadingTask.startTask();
        UploadingTask.uploadStrain(getContext(),lowStrainDb);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadHighStrain(HighStrain highStrain)
    {
        UploadingTask.startTask();
        UploadingTask.uploadHighStrainData(highStrain,getContext());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadStatic(StaticLoad staticLoad)
    {
        UploadingTask.startTask();
        UploadingTask.uploadStaticLoad(staticLoad,getContext());
    }

    @OnClick(R.id.Take_Photo)
    public void takePhoto(View view)
    {
        if (workingPlan == null || workingPlan.equals(""))
        {
            showMessageDialog("请先选择报检单");
            return;
        }
        InspectionForm.InspectionFormListBean inspectionForm =
                JSON.parseObject(workingPlan, InspectionForm.InspectionFormListBean.class);
        Intent intent = new Intent(getContext(),PhotoActivity.class);
        intent.putExtra(PhotoActivity.PHOTO_INTENT,inspectionForm);
        switch (planMode)
        {
            case road:
                intent.putExtra(PhotoActivity.PLAN_INTENT,1);
                break;

            case bridge:
                intent.putExtra(PhotoActivity.PLAN_INTENT,0);
                break;
        }
        startActivity(intent);
    }

}
